package logic

import (
	"context"
	"encoding/json"

	"googee/common/errorx"
	"googee/service/account/api/internal/svc"
	"googee/service/account/api/internal/types"
	"googee/service/account/rpc/types/account"

	_ "github.com/dtm-labs/driver-gozero"
	_ "github.com/dtm-labs/dtmdriver-gozero"
	"github.com/dtm-labs/dtmgrpc"
	"github.com/fatih/color"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type TransLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTransLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TransLogic {
	return &TransLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TransLogic) Trans(req *types.TransReq) (resp *types.UserInfoReply, err error) {
	//FIXME: 转账数目的参数要改成float类型的
	resp = &types.UserInfoReply{}

	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	accountRpcBusiServer, err := l.svcCtx.Config.Account.BuildTarget()
	if err != nil {
		return nil, status.Error(codes.Internal, "系统内部错误")
	}

	gid := dtmgrpc.MustGenGid(l.svcCtx.Config.DtmServer)
	err = dtmgrpc.TccGlobalTransaction(l.svcCtx.Config.DtmServer, gid, func(tcc *dtmgrpc.TccGrpc) error {

		req1 := &account.TransInRequest{
			Id:      id,
			Field:   req.Field,
			Amount:  req.Amount,
			TransId: gid,
			Typ:     "account",
			Subtyp:  "trans",
		}

		tryUrl := accountRpcBusiServer + "/account.Account/transOutTry"
		confirmlUrl := accountRpcBusiServer + "/account.Account/transOutConfirm"
		cancelUrl := accountRpcBusiServer + "/account.Account/transOutCancel"

		err := tcc.CallBranch(req1, tryUrl, confirmlUrl, cancelUrl, &account.Empty{})
		if err != nil {
			return err
		}

		req2 := &account.TransOutRequest{
			Id:      req.Id,
			Field:   req.Field,
			Amount:  req.Amount,
			TransId: gid,
			Typ:     "account",
			Subtyp:  "trans",
		}
		tryUrl = accountRpcBusiServer + "/account.Account/transInTry"
		confirmlUrl = accountRpcBusiServer + "/account.Account/transInConfirm"
		cancelUrl = accountRpcBusiServer + "/account.Account/transInCancel"
		return tcc.CallBranch(req2, tryUrl, confirmlUrl, cancelUrl, &account.Empty{})
	})

	if err != nil {
		color.Red("err=%v", err)
		return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "转账失败")
	}

	return
}
